一、定时任务触发条件

1、在 Application 启动类上添加:@EnableScheduling

2、含定时方法的类上添加注解:@Component,该注解将定时任务类纳入 spring bean 管理。

3、在定时方法上写上:@Scheduled(cron = "0 0/1 * * * ?"),该 cron 表达式为每一分钟执行一次方法。

二、@Scheduled用法

1、fixedDelay

1
2
3
4
5
6
7
8
9
@Scheduled(fixedDelay = 5000)
public void testFixedDelay(){
try {
log.info("当前时间:" + DateUtil.now());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

每个任务延迟3秒,然后打印当前时间。

fixedDelay规律总结:

程序启动后即刻触发。前一个任务执行结束后,再等待5秒,然后执行第二个任务。

2、fixedRate

1
2
3
4
5
6
7
8
9
@Scheduled(fixedRate = 5000)
public void testFixedRate(){
try {
log.info("当前时间:" + DateUtil.now());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

任务启动后,每隔5秒执行一次任务。

如果将延时时间修改为8秒,则输出变为8秒,如下图所示:

fixedRate规律总结:

程序启动后即刻触发。假如设置定时任务每5秒一执行,如果前一个任务用时超过了5秒,则等前一个任务完成后就立刻执行第二次任务。如果前一个任务用时小于5秒,则等满足5秒以后,再执行第二次任务。

3、Corn表达式详解(常用)

Corn 表达式可用 秒、分、时、天、周、月、年 来表示:

1
2
3
4
秒	分	时	天	周	月	年

0 * 14 * * ? * : 代表每天从14点开始,每一分钟执行一次。
0 0 14 * * ? * : 代表每天的14点执行一次任务。

可使用 Corn 在线生成表达式:http://cron.qqe2.com/,来检测 Cron 的合理性。

Corn 示例:每2分钟执行一次。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Scheduled(cron = "0 0/2 * * * ?")
public void test() {
int j = 0;
for (int i = 0; i < 10; i++) {
log.info("Scheduled测试");
j++;
log.info("j的值为:" + j);
try {
Thread.sleep(1000 * 20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

效果:

总结

如上述代码所示,设置 test() 方法每2分钟执行一次。但如果前一个任务执行时长超过了2分钟,则第二个任务会等待前一个任务完成后的一段时间后再执行第二个任务。

三、@Scheduled 定时时间可配置

1
2
3
4
@Scheduled(cron = "${cronConf.test:0 0 06 * * ?}")
public void test() {
...
}

cronConf.test在 application.yml 配置文件中:

1
2
cronConf:
test: 0 0/60 * * * ?

四、spring boot @Scheduled 开关

我们有时在部署测试环境时,并不需要定时任务执行,再去掉注解显然太麻烦,这时我们可以给定时任务加个开关。

1
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")

将上述代码拷贝到执行定时任务的类上,然后 application.yml 配置文件上添加:

1
2
scheduling:
enabled: false

当 scheduling.enabled 值为 false 时,定时不触发。

@ConditionalOnProperty的意思是:

  • prefix:application.properties 配置的前缀。
  • name:属性是从 application.properties 配置文件中读取属性值。
  • havingValue:配置读取的属性值跟 havingValue 做比较,如果一样则返回 true ; 否则返回 false 。如果返回值为 false ,则该 configuration不生效;为 true 则生效。
  • matchIfMissing = true 表示如果没有在 application.properties 设置该属性,则默认为条件符合。

参考博客: